<?php
namespace Api\Controller\Amazon;
use \Home\Controller\CommonController;
use \Inbound\Service\PublicInfoService;
use \Inbound\Service\PublicPlugService;

class FbaStockingArgsController extends CommonController{
    public $reportSaleService = NULL;
    public $accountsService = NULL;
    public $purchaseOrdersService = NULL;
    public $inventoryService = NULL;

    public function __construct(){
        $this->reportSaleService = D('Amazon\ReportSale','Service');
        $this->purchaseOrdersService = D('Warehouse/PurchaseOrders','Service');
        $this->inventoryService = D('Warehouse/Inventory', 'Service');
        $this->accountsService = D('Amazon\Accounts','Service');

        parent::__construct();
    }

    /**
     * 描述：首页展示
     */
    public function index(){
        $this->display();
    }

    /**
     * 描述：获取报告
     */
    public function getReport(){
        if (isset($_POST['sku']) && $_POST['sku']) {
            $sku = explode(',', $_POST['sku']);
            if (count($sku) > 5) {
                $message['count'] = 1;
                $message['message'] = '超过5个SKU,请上传文件!';
                echo json_encode($message);
                exit;
            }

            $reportStockSaleData = $this->reportSaleService->selectData(array('sku' => '\'' . implode('\',\'', $sku) . '\'' ));

            $actualInventory = PublicInfoService::getSiteActualInventory($sku);
            $onWayInventory = PublicInfoService::getInternalOnWayStock($sku);

            $enterprise_dominant = PublicInfoService::get_company_array();
            $sites = PublicInfoService::get_site_array();

            $siteActualInventory = array();
            $siteOnWayInventory = array();
            if (!empty($actualInventory)) {
                foreach ($actualInventory as &$data) {
                    $data['site_id'] = $sites[$data['site_id']];
                    $siteActualInventory[$data['sku'] .':'. $data['enterprise_dominant'] .':'.$data['site_id']] = $data['available_quantity'];
                }
            }
            if (!empty($onWayInventory)) {
                foreach ($onWayInventory as &$data) {
                    $data['site_id'] = $sites[$data['site_id']];
                    $siteOnWayInventory[$data['sku'] .':'. $data['enterprise_dominant'] .':'.$data['site_id']] = $data['onwayStock'];
                }

            }

            foreach ($reportStockSaleData as &$data) {
                foreach ($enterprise_dominant as $num => $dominant) {
                    $data[$num . ':actual'] = isset($siteActualInventory[$data['private_sku'] .':'. $num . ':' . $data['shorthand_code']])
                        ? $siteActualInventory[$data['private_sku'] .':'.$num . ':' . $data['shorthand_code']] : 0;
                    $data[$num . ':onway'] = isset($siteOnWayInventory[$data['private_sku'] .':'.$num . ':' . $data['shorthand_code']])
                        ? $siteOnWayInventory[$data['private_sku'] .':'.$num . ':' . $data['shorthand_code']] : 0;
                    $data['totalActual'] += $data[$num . ':actual'];
                    $data['totalOnway'] += $data[$num . ':onway'];
                }
            }

            echo json_encode($reportStockSaleData);
            exit;
        }
    }

    /**
     * 描述：下载模板
     */
    public function skuDownload() {
        PublicPlugService::download_templet_xlsx();
    }

    /**
     * 描述：上传下载
     */
    public function upload_sku() {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $sheetData = PublicPlugService::parse_excel();                            //解析excel内容
        if(!$sheetData) {
            echo "<script>alert('文件内容解析有误，请检查文件内容');history.go(-1)</script>";
            exit;
        }

        if(!PublicPlugService::$flag){                                            //选择了上传文件,状态返回false
            if(count($sheetData)>=2){
                foreach ($sheetData as $k=>&$v){
                    if($k==1) continue;
                    if (!trim($v['A'])) break;
                    $sku[] = trim($v['A']);
                }


                $mainAccountName = PublicInfoService::getMainAccountName();
                $reportStockSaleData = $this->reportSaleService->selectData(array('sku' => '\'' . implode('\',\'', $sku) . '\''));

                $actualInventory = PublicInfoService::getSiteActualInventory($sku);
                $onWayInventory = PublicInfoService::getInternalOnWayStock($sku);

                $enterprise_dominant = PublicInfoService::get_company_array();
                $sites = PublicInfoService::get_site_array();
                $siteActualInventory = array();
                $siteOnWayInventory = array();
                if (!empty($actualInventory)) {
                    foreach ($actualInventory as &$data) {
                        $data['site_id'] = $sites[$data['site_id']];
                        $siteActualInventory[$data['sku'] .':'.$data['enterprise_dominant'] .':'.$data['site_id']] = $data['available_quantity'];
                    }
                }
                if (!empty($onWayInventory)) {
                    foreach ($onWayInventory as &$data) {
                        $data['site_id'] = $sites[$data['site_id']];
                        $siteOnWayInventory[$data['sku'] .':'.$data['enterprise_dominant'] .':'.$data['site_id']] = $data['onwayStock'];
                    }

                }

                foreach ($reportStockSaleData as &$data) {
                    $data['mainAccount'] =  $data['private_sku'] . "-" . $data['accountName'] . "-" . $data['shorthand_code']. "-" . $data['asin'];
                    foreach ($enterprise_dominant as $num => $dominant) {
                        $data[$num . ':actual'] = isset($siteActualInventory[$data['private_sku'] .':'.$num . ':' . $data['shorthand_code']])
                            ? $siteActualInventory[$data['private_sku'] .':'.$num . ':' . $data['shorthand_code']] : 0;
                        $data[$num . ':onway'] = isset($siteOnWayInventory[$data['private_sku'] .':'.$num . ':' . $data['shorthand_code']])
                            ? $siteOnWayInventory[$data['private_sku'] .':'.$num . ':' . $data['shorthand_code']] : 0;
                        $data['totalActual'] += $data[$num . ':actual'];
                        $data['totalOnway'] += $data[$num . ':onway'];
                    }
                }

                $excelFileName = 'FBA备货参数';
                $firstLine = array(
                    'sellerName'            => '销售员',
                    'shorthand_code'        => '站点',
                    'accountName'           => '店铺帐号',
                    'mainAccount'           => '虚拟SKU',
                    'sku'                   => 'SellerSKU',
                    'asin'                  => 'ASIN',
                    'daysale'               => '日均销量',
                    'private_sku'           => '公司SKU',
                    'item'                  => '品名',
                    'inventory'             => 'FBA库存',
                    'unsuppressedInventory' => '国际在途',
                    'air'                   => '空运在途',
                    'ocean'                 => '海运在途',
                    'homeNum'               => '待发货数',
                    'saleStatus'            => '销售状态',
                    '1:actual'              => '有棵树电子商务有限公司(可用库存)',
                    '1:onway'               => '有棵树电子商务有限公司(在途库存)',
                    '2:actual'              => '杭州有棵树科技有限公司(可用库存)',
                    '2:onway'               => '杭州有棵树科技有限公司(在途库存)',
                    '3:actual'              => '深圳市有棵树科技股份有限公司(可用库存)',
                    '3:onway'               => '深圳市有棵树科技股份有限公司(在途库存)',
                    '4:actual'              => '深圳市有棵树电子商务有限公司(可用库存)',
                    '4:onway'               => '深圳市有棵树电子商务有限公司(在途库存)',
                    'totalActual'           => '总可用库存',
                    'totalOnway'            => '总在途库存'
                );

                $this->download($reportStockSaleData, $firstLine, $excelFileName);

            }else{
                echo "<script>alert('文件内容为空');history.go(-1)</script>";die;
            }
        }else{
            echo '<script>alert("请选择上传文件");history.go(-1)</script>';die;
        }
    }

    /**
     * @param $data
     * @param $firstLine
     * @param string $excelFileName
     * 描述：下载
     */
    public function download($data, $firstLine = array(), $excelFileName) {
        set_time_limit(0);
        ini_set('memory_limit','1024M');

        /* 获取字段名称 */
        $keys    = array_keys($firstLine);
        $content = "";
        $content .= "<table border='1'><tr>";
        foreach($firstLine as $_pre){
            $content .= "<td>$_pre</td>";
        }
        $content .= "</tr>";
        foreach($data as $_list){
            $content .= "<tr>";
            foreach($keys as $key){
                $content .= "<td style='vnd.ms-excel.numberformat:@'>".$_list[$key]."</td>";
            }
            $content .= "</tr>";
        }
        $content .= "</table>";
        header("Content-type:application/vnd.ms-execl;charset=gb2312");
        header("Content-Disposition:attactment;filename=".$excelFileName.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        echo $content;
        exit;
    }

    public function sku_quantity() {
        $accounts = $this->accountsService->getAccounts();
        $condition = array_filter($_POST);


        if (!empty($condition)) {
            !empty($condition['sku']) && $condition['sku'] = trim($_POST['sku']);

            $data = $this->reportSaleService->getSkuQuantity($condition);
            $totalAmount = 0;
            $cancel_count = 0;

            foreach ($data as &$v) {
                $totalAmount += $v['quantity'];
                $v['virtual_sku'] = $v['private_sku'] . '-' . $v['name'] . '-' . $v['shorthand_code'] . '-' . $v['asin'];
                if ($v['order_status'] == 'Cancelled') $cancel_count += $v['quantity'];
            }

            if ($condition['download']) {
                $excelFileName = "FBA订单销量统计报表";
                $firstLine = array(
                    'amazon_order_id' => '订单号',
                    'purchase_date' => '下单时间',
                    'sku' => 'SKU',
                    'virtual_sku' => '虚拟SKU',
                    'order_status' => '订单状态',
                    'quantity' => '个数'
                );

                $this->download($data, $firstLine, $excelFileName);
            }

            $mount['totalAmount'] = $totalAmount;
            $mount['cancel_count'] = $cancel_count;
            $mount['valid_count'] = $totalAmount - $cancel_count;

            $this->assign('data', $data);
            $this->assign('mount', $mount);
            $this->assign('condition', $condition);
        }

        $this->assign('accounts', $accounts);
        $this->display('sku_quantity');
    }

    /**
     * 描述：分别下载销量、国际在途库存、库存数据
     * 作者：橙子
     */
    public function singleDownload() {
        ini_set('memory_limit','2048M');
        $this->reportSaleService->downloadSingleData($_GET['downloadType']);
    }
}